<?php

namespace Drupal\shushengyuan\Schemas;

use Drupal\shusy_pintuan\Entity\ShusyPintuan;

/**
 * @OA\Schema(
 *   schema="ProductPtingItem",
 *   type="object",
 *   description="ProductPtingItem"
 * )
 */
class ProductPtingItem extends AbstractBaseModel {

  protected function getEntityType() {
    return 'shusy_pintuan';
  }

  protected function setValue() {
    if ($this->entity instanceof ShusyPintuan) {
      $value = [
        /**
         * @OA\Property(
         *   property="id",
         *   type="integer",
         *   description="ID",
         * ),
         */
        'id' => (int) $this->entity->id,
        /**
         * @OA\Property(
         *   property="pid",
         *   type="integer",
         *   description="拼的产品ID",
         * ),
         */
        'pid' => (int) $this->entity->product_id,
        /**
         * @OA\Property(
         *   property="user",
         *   ref="#/components/schemas/User",
         *   description="拼主",
         * ),
         */
        'user' => User::get($this->entity->uid),
        /**
         * @OA\Property(
         *   property="validity",
         *   type="integer",
         *   description="有效期剩余秒",
         * ),
         */
        'validity' => (int) ($this->entity->validity - REQUEST_TIME),
        /**
         * @OA\Property(
         *   property="date",
         *   ref="#/components/schemas/Date",
         *   description="倒计时信息",
         * ),
         */
        'date' => Date::get(FALSE, FALSE, [($this->entity->validity - REQUEST_TIME)]),
        /**
         * @OA\Property(
         *   property="vacancy",
         *   type="integer",
         *   description="差几人",
         * ),
         */
        'vacancy' => (int) $this->getVacancy(),
        /**
         * @OA\Property(
         *   property="players",
         *   type="array",
         *   description="参与拼的用户 不包含拼主 最多返回5个",
         *   @OA\Items(ref="#/components/schemas/User")
         * ),
         */
        'players' => $this->getPlayers(),
      ];
      $this->merge($value);
    }
  }

  protected function getPlayers() {
    $query = db_select('shusy_pintuan_player', 't');
    $query->fields('t', ['id', 'uid']);
    $query->condition('pintuan_id', $this->entity->id);
    //$query->condition('uid', $this->entity->uid, '<>');
    $query->condition('status', [1], 'IN');
    $query->orderBy('id');
    $query->range(1, 5);
    $result = $query->execute();
    $list = [];
    while ($row = $result->fetchAssoc()) {
      $list[] = User::get($row['uid']);
    }
    return $list;
  }

  protected function getVacancy() {
    $query = db_select('shusy_pintuan_player', 't');
    $query->fields('t', ['id']);
    $query->condition('pintuan_id', $this->entity->id);
    $query->condition('status', [1], 'IN');
    $query->orderBy('id');
    return ($this->entity->number - $query->execute()->rowCount());
  }
}
